package com.dazhi.show.menu.controller;

import com.dazhi.show.core.Result;
import com.dazhi.show.menu.dao.Menu;
import com.dazhi.show.menu.service.MenuService;
import com.dazhi.show.menu.vo.MenuVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/menu")
public class MenuController {
    @Autowired
    private MenuService menuService;

    @GetMapping
    public Result<List<MenuVo>> menus() {
        /*List<MenuVo> menus = new ArrayList<>();
        MenuVo menu1 = new MenuVo(1,"Learn菜单管理",1,"",0);
        List<MenuVo> menu1_1 = new ArrayList<>();
        menu1_1.add(new MenuVo(2,"Learn管理",2,"",1));
        menu1.setChild(menu1_1);
        menus.add(menu1);

        MenuVo menu2 = new MenuVo(10,"Life菜单管理",1,"",0);
        List<MenuVo> menu2_1 = new ArrayList<>();
        menu2_1.add(new MenuVo(11,"Life管理",2,"",10));
        menu2.setChild(menu2_1);
        menus.add(menu2);*/
        List<Menu> menuList = menuService.list();
        // 将menuList封装
        // 处理2级菜单
        Map<Integer,List<MenuVo>> menu2 = new HashMap<>();
        for (Menu menu : menuList){
            if (menu.getLeval() == 2){
                List<MenuVo> menuList2 = menu2.get(menu.getParentId());
                if (null == menuList2){
                    menuList2 = new ArrayList<>();
                    menu2.put(menu.getParentId(),menuList2);
                }
                menuList2.add(new MenuVo(menu));
            }
        }
        List<MenuVo> menus = new ArrayList<>();
        for (Menu menu : menuList){
            if (menu.getLeval() == 1){
                MenuVo menuVo = new MenuVo(menu);
                menuVo.setChild(menu2.get(menu.getId()));
                menus.add(menuVo);
            }
        }

        return new Result<List<MenuVo>>(200,"success", menus);
    }
}
